const app = getApp();
import grace from "../../../utils/grace.js";

grace.page({
  /**
   * 页面的初始数据
   */
  data: {
      orderStates: ['all', 'sale', 'done'],
      orderStateStrs: ['全部', '待付款', '已付款'],
      currentIndex: 0,
      currentState: 'all',
      orderList: [],
      total: 0,
      page: 1,
      pagesize: 10
  },
  onLoad(e) {
    if(e.state){
      this.$data.currentIndex = e.state;
      this.$data.currentState = this.$data.orderStates[e.state];
    }
  },
  onShow() {
    let token = wx.getStorageSync('token');
    if(!token){
      wx.navigateTo({
        url: '/pages/common/authorize/index'
      })
      return;
    }

    this.$data.page = 1;
    this.$data.orderList = [];
    this.getList();
  },
  statesTap (e) {
    this.$data.page = 1;
    this.$data.orderList = [];
    this.$data.currentIndex = e.currentTarget.dataset.index;
    this.$data.currentState = this.$data.orderStates[e.currentTarget.dataset.index];
    this.onShow();
  },
  orderDetail(e) {
    var orderId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: "/pages/mall/order/detail?id=" + orderId
    })
  },
  getList() {
    wx.showLoading({
      title: '加载中...',
    })
    let school_id = wx.getStorageSync('school_id')
    let url = app.globalData.api + '/api/v1.0/guardian/orders/' + school_id + '/' + wx.getStorageSync('partner_id') + '/' + this.$data.currentState + '?page=' + this.$data.page + '&pagesize=' + this.$data.pagesize;
    this.$http.get(url, { token: wx.getStorageSync('token') }).then((res) => {
      if (res.data.code == 0) {
        this.$data.total = res.data.data.total;
        this.$data.page = this.$data.page + 1;
        this.$data.orderList = this.$data.orderList.concat(res.data.data.list);
      } else if (res.data.code == 10001) {
        wx.navigateTo({
          url: "/pages/common/authorize/index"
        })
      }else {
        this.$data.orderList = [];
      }
      wx.hideLoading();
    }).catch(err => {
      console.log(err.status, err.message);
    });
  },
  onReachBottom () {
    if(this.$data.orderList.length < this.$data.total){
      this.getList();
    }
  }
})